<template>
    <view class="wai">
        <view class="list-top">
            <view class="list1">
                <view>商品名称</view>
                <input v-model="addData.title" class="input" type="text" placeholder="请输入商品名称" />
            </view>
            <!--        <view class="list1">
                <view>价格（元）</view>
                <input class="input" type="text" placeholder="请输入现价" />
            </view> -->
            <!--  <view class="list1">
                <view>库存数量</view>
                <input class="input" type="text" placeholder="请输入库存数量" />
            </view> -->
            <view class="list2">
                <!-- <uni-combox :id="myInput" :candidates="candidates.name" placeholder="分类"></uni-combox> -->
                <uni-section title="是否可清除已选项" type="line">
                    <uni-data-select placeholder="分类" v-model="value" :localdata="range" @change="change" :clear="false"></uni-data-select>
                </uni-section>
            </view>
        </view>
        <view class="cen-sp">
            <view>上传商品主图（一张）</view>
            <view class="flex" @click="addImg">
                <image v-if="addData.image" class="image" :src="getImg" mode=""></image>
                <image v-else class="image" src="@/static/upload.png" mode=""></image>
            </view>
        </view>
        <view class="cen-sp">
            <view>填写商品详情（多张）</view>
            <textarea v-model="addData.subtitle" class="textarea" cols="30" rows="10" placeholder="请输入详细信息"></textarea>
            <view v-if="fullurls.length <= 0" class="flex" @click="addsImg">
                <image class="image" src="@/static/upload.png" mode=""></image>
            </view>
            <view v-else class="flex" @click="addsImg">
                <image v-for="(it, index) in fullurls" :key="index" class="image" :src="it" mode=""></image>
            </view>
        </view>
        <view class="cen-sp" v-for="(item, index) in addData.skus" :key="index">
            <view class="ions">
                <view class="">填写规格</view>
                <view v-if="index == 0" class="rightadd" @click="addSku(item)">点击添加多个规格</view>
            </view>
            <view class="guige">
                <input class="inp" type="text" v-model="item.name" placeholder="请填写商品规格" />
            </view>
            <view v-for="(it, index1) in item.children" :key="index1">
                <view class="ions">
                    <view class="">填写商品类型，库存和价格(元)</view>
                    <view v-if="index1 == 0" class="rightadd" @click="addleixing(index)">添加多个类型</view>
                </view>
                <view class="guige">
                    <input @blur="blur1($event, index1, it)" v-model="it.name" class="inp" type="text" placeholder="请填写类型" />
                </view>
                <view class="guige">
                    <input @blur="blur2($event, index1, it)" v-model="it.stock" class="inp" type="text" placeholder="请填写库存" />
                </view>
                <view class="guige">
                    <input @blur="blur3($event, index1, it)" v-model="it.price" class="inp" type="text" placeholder="请填写价格" />
                </view>
            </view>
        </view>
        <view class="topjia">
            <view>是否立即上架</view>
            <wd-switch @change="change1" v-model="checked" active-color="#FF9B29" size="25" />
        </view>
        <view class="topjia">
            <view>自提</view>
            <wd-switch v-model="ziti" active-color="#FF9B29" size="25" />
        </view>
        <view class="btn" @click="btnClick">确定</view>
    </view>
</template>

<script setup>
import { goodsCategory, addGoods } from '@/api/index.js';
import { uploadFile, uploadFiles } from '@/utils/request.js';
import { utils } from '@/utils/utils.js';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { ref, onMounted } from 'vue';
const ziti = ref(true); //自提
const getImg = ref(''); //主图
const range = ref([]); //分类列表
const checked = ref(true); //是否上架
const linshiId = ref(1); //临时id
const fullurls = ref([]); //详情图显示的路径
const addData = ref({
    title: '', //标题
    image: '', //主图
    subtitle: '', //副标题
    images: [], //详情图
    category_ids: '', //商品分类
    is_sku: '1', //，默认1
    content: '', //详情
    status: 'up', //是否上架，默认上架，
    skus: [
        {
            id: '0', //没有传0
            name: '', //规格
            goods_id: '0', //没有传0
            parent_id: '0', //没有传0
            temp_id: linshiId.value, //临时id
            children: [
                {
                    id: '0', //没有传0
                    name: '', //类型
                    goods_id: '0', //没有传0
                    parent_id: '0', //没有传0
                    temp_id: linshiId.value //临时id
                }
            ]
        }
    ],
    sku_prices: [
        {
            id: '0', //没有传0
            temp_id: linshiId.value, //临时id需要与children里的对应
            goods_id: '0', //没有传0
            stock: '', //库存
            price: '', //价格
            status: 'up', //是否上架，默认上架，
            goods_sku_text: [], //颜色
            goods_sku_temp_ids: [linshiId.value] //临时id需要与children里的对应
        }
    ]
}); //上传的参数
onLoad(() => {
    getGoodList(); //获取分类
});
//上传主图
const addImg = async () => {
    const ret = await uploadFile();
    getImg.value = ret.data.fullurl; //显示的图片路径
    addData.value.image = ret.data.url; //参数的图片路径
};
// 上传详情图
const addsImg = async () => {
    const ret = await uploadFiles();
    // 分离 fullurl（显示的路径） 和 url （参数的路径）
    fullurls.value = ret.map((item) => item.fullurl); //显示的图片路径
    addData.value.images = ret.map((item) => item.url); //参数的图片路径
};

// 输入框失去焦点触发
const blur1 = (e, index, it) => {
    const matchedItem = addData.value.sku_prices.find((item) => {
        return item.goods_sku_temp_ids == it.temp_id;
    });
    if (matchedItem) {
        console.log('找到匹配的元素:', matchedItem);
        // matchedItem.goods_sku_text = e.detail.value;
        matchedItem.goods_sku_text[0] = e.detail.value;
    }
};
const blur2 = (e, index, it) => {
    const matchedItem = addData.value.sku_prices.find((item) => {
        return item.goods_sku_temp_ids == it.temp_id;
    });
    if (matchedItem) {
        console.log('找到匹配的元素:', matchedItem);
        matchedItem.stock = e.detail.value;
    }
};
const blur3 = (e, index, it) => {
    const matchedItem = addData.value.sku_prices.find((item) => {
        return item.goods_sku_temp_ids == it.temp_id;
    });
    if (matchedItem) {
        console.log('找到匹配的元素:', matchedItem);
        matchedItem.price = e.detail.value;
    }
};
// 点击添加类型
const addleixing = (index) => {
    linshiId.value++;
    addData.value.sku_prices.push({
        id: '0', //没有传0
        temp_id: linshiId.value, //临时id需要与children里的对应
        goods_id: '0', //没有传0
        stock: '', //库存
        price: '', //价格
        status: 'up', //是否上架，默认上架，
        goods_sku_text: [], //颜色
        goods_sku_temp_ids: [linshiId.value] //临时id需要与children里的对应
    });
    addData.value.skus[index].children.push({
        id: '0', //没有传0
        name: '', //类型
        goods_id: '0', //没有传0
        parent_id: '0', //没有传0
        temp_id: linshiId.value //临时id
    });
};

//点击添加多个规格
const addSku = (item) => {
    linshiId.value++;
    addData.value.skus.push({
        id: '0', //没有传0
        name: '', //规格
        goods_id: '0', //没有传0
        parent_id: '0', //没有传0
        temp_id: linshiId.value, //临时id
        children: [
            {
                id: '0', //没有传0
                name: '', //类型
                goods_id: '0', //没有传0
                parent_id: '0', //没有传0
                temp_id: linshiId.value //临时id
            }
        ]
    });
    addData.value.sku_prices.push({
        id: '0', //没有传0
        temp_id: linshiId.value, //临时id需要与children里的对应
        goods_id: '0', //没有传0
        stock: '', //库存
        price: '', //价格
        status: 'up', //是否上架，默认上架，
        goods_sku_text: [], //颜色
        goods_sku_temp_ids: [linshiId.value] //临时id需要与children里的对应
    });
};
// 确认
const btnClick = async () => {
    if (addData.value.title == '') return utils('标题不能为空');
    if (addData.value.category_ids == '') return utils('请选择分类');
    if (addData.value.image == '') return utils('主图不能为空');
    if (addData.value.subtitle == '') return utils('请输入商品详情');
    if (addData.value.images.length <= 0) return utils('请选择详情图');
    // addData.value.subtitle = addData.value.title;
    const ret = await addGoods(JSON.stringify(addData.value));
    if (ret.code == 1) {
        uni.navigateBack({
            delta: 2 // 可选参数，表示要返回的页面数，默认为 1
        });
        utils('添加成功');
    } else {
        utils(ret.msg);
    }
    console.log(111, ret);
};
// 获取商品分类
const getGoodList = async () => {
    const ret = await goodsCategory();
    console.log(ret.data);
    if (ret.code == 1) {
        range.value = ret.data.map((item) => ({
            ...item,
            text: item.name, // 将 name 的值赋给新的 text 属性
            value: item.id
        }));
    } else {
        utils();
    }
};
//点击开关是否上架
const change1 = ({ value }) => {
    if (value) {
        addData.value.status = 'up';
        addData.value.sku_prices.forEach((it) => {
            it.status = 'up';
        });
    } else {
        addData.value.status = 'down';
        addData.value.sku_prices.forEach((it) => {
            it.status = 'down';
        });
    }
};
//选中分类的值
const change = (e) => {
    addData.value.category_ids = e;
};
</script>

<style lang="scss" scoped>
.guige {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // background-color: pink;
    padding: 30rpx;
    height: 80rpx;
    margin: 20rpx 0;
    border: solid #dadada 2rpx;
    border-radius: 12rpx;
    .inp {
        flex: 1;
    }
    .addvw {
        padding: 15rpx;
    }
}
.wai {
    .btn {
        color: #ffffff;
        background: #ff9b29;
        border-radius: 50rpx;
        width: 702rpx;
        height: 80rpx;
        text-align: center;
        line-height: 80rpx;
        margin-left: 24rpx;
        margin-top: 50rpx;
    }
    // 是否自动上架
    .topjia {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 120rpx;
        background-color: #fff;
        margin: 20rpx 0;
        padding: 0 24rpx;
    }
    // 上传主图
    .cen-sp {
        .ions {
            .rightadd {
                color: #ff9b29;
            }
            justify-content: space-between;
            display: flex;
            align-content: center;
        }
        .textarea {
            background-color: #f0f0f0;
            height: 160rpx;
            width: 650rpx;
            padding: 24rpx;
            border-radius: 15rpx;
            margin-top: 18rpx;
        }
        .flex {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            .image {
                width: 220rpx;
                height: 220rpx;
                margin-top: 18rpx;
                margin-right: 20rpx;
                &:nth-child(3n) {
                    margin-right: 0;
                }
            }
        }
        padding: 34rpx 24rpx 32rpx;
        background-color: #fff;
        margin-top: 20rpx;
    }
    // 顶部信息
    .list-top {
        .list2 {
            padding: 24rpx 0;
            height: 120rpx;
        }
        .list1 {
            .input {
                text-align: end;
            }
            border-bottom: solid #f5f5f5 2rpx;
            height: 104rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        background-color: #fff;
        padding: 0 24rpx;
    }
    min-height: 100vh;
    background-color: #f7f7f7;
    padding-bottom: 80rpx;
}
</style>
